<template>
  <div>
    <div
      style="padding-top: 30px"
      v-if="showSearch"
      :class="{
        'enter-level flipInX': showSearch,
      }"
    >
      <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
        <el-form-item label="角色名称">
          <el-input
            v-model="searchFrom.roleName"
            placeholder="请输入角色名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input
            v-model="searchFrom.roleKey"
            placeholder="请输入权限字符"
            clearable
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="searchFrom.status"
            placeholder="角色状态"
            clearable
          >
            <el-option label="正常" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :icon="Search">
            搜索
          </el-button>
          <el-button type="info" @click="reset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="padding: 30px">
      <div
        style="
          padding-bottom: 20px;
          display: flex;
          justify-content: space-between;
        "
      >
        <div>
          <el-button :icon="Plus" type="success" @click="insertOne"
            >新增</el-button
          >
          <el-popconfirm
            title="确定删除吗？"
            @confirm="batchDel"
            @cancel="cancelEvent"
          >
            <template #reference>
              <el-button type="danger" :icon="Delete" :disabled="isBatch">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </div>
        <div>
          <el-button
            :icon="Search"
            circle
            @click="showSearch = !showSearch"
          ></el-button>
          <el-button :icon="Refresh" circle @click="reset"></el-button>
        </div>
      </div>
      <el-table
        ref="multipleTableRef"
        :data="dataList"
        style="width: 100%"
        max-height="600"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="selectable" />
        <el-table-column
          type="index"
          :index="indexMethod"
          label="角色编号"
          width="120"
        />
        <el-table-column property="roleName" label="角色名称" />
        <el-table-column property="roleKey" label="权限字符" />

        <el-table-column label="状态">
          <template #default="scope">
            <el-switch
              :disabled="scope.row.roleKey === 'admin'"
              v-model="scope.row.status"
              class="ml-2"
              inline-prompt
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
              :before-change="changeStatus.bind(this, scope.row.roleId)"
              active-text="开启"
              :active-value="1"
              :inactive-value="0"
              inactive-text="关闭"
            />
          </template>
        </el-table-column>
        <el-table-column property="role_sort" label="显示顺序" />
        <el-table-column label="创建时间" width="200">
          <template #default="scope">{{
            tool.formatDateToYYYYMMDD(scope.row.createTime)
          }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="300">
          <template #default="scope">
            <div v-if="scope.row.roleKey !== 'admin'">
              <el-button
                @click="oper(scope.row, 1)"
                type="text"
                :icon="EditPen"
              >
                修改
              </el-button>
              <el-popconfirm
                title="确定删除吗？"
                @confirm="oper(scope.row.roleId, 2)"
                @cancel="cancelEvent"
              >
                <template #reference>
                  <el-button type="text" :icon="Delete"> 删除 </el-button>
                </template>
              </el-popconfirm>
              <el-dropdown placement="bottom">
                <el-button type="text" :icon="DArrowRight"> 更多 </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <el-icon><Share /></el-icon>
                      角色权限
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-icon><User /></el-icon>
                      分配用户
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <add-Role
    ref="addDataRef"
    @common="handlerCommon"
    :roleList="roleList"
  ></add-Role>
</template>

<script setup>
import request from "@/assets/js/request";
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import addRole from "@/components/setting/add-role.vue";
import tool from "@/assets/js/tool";
import {
  Search,
  Refresh,
  EditPen,
  DArrowRight,
  Delete,
  Plus,
  User,
  Share,
} from "@element-plus/icons-vue";

const showSearch = ref(true);
const searchFrom = ref({
  roleName: "",
  roleKey: "",
  status: null,
});

const addDataRef = ref();
const selectable = ref();
const dataList = ref([]);
const isBatch = ref(true);
const selectData = ref([]);
const roleList = ref([]);

const indexMethod = (index) => {
  return index + 1;
};

//获取数据
const getDataList = () => {
  request
    .post(`/role/list`, searchFrom.value)
    .then((res) => {
      if (res.code === 200) {
        dataList.value = res.data;
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

const cancelEvent = () => {
  selectData.value = [];
};

// 新增数据
const insertOne = () => {
  addDataRef.value.open(null, 0);
};

// 数据操作
const oper = (key, type) => {
  if (type == 1) {
    addDataRef.value.open(key, 1);
    return;
  } else {
    selectData.value = [key];
    batchDel();
  }
};

const getMenuList = () => {
  request
    .get("/admin/menu/list")
    .then((res) => {
      if (res.code === 200) {
        roleList.value = res.data;
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

const changeStatus = async (data) => {
  return new Promise((resolve) => {
    ElMessageBox.confirm("继续操作吗？", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      await limit(data);
      // await getDataList();
      return resolve(true);
    });
  });
};

const limit = (data) => {
  request
    .get(`/role/limit?rid=${data}`)
    .then((res) => {
      console.log(res);
      ElMessage.success("操作成功");
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

const handlerCommon = (item) => {
  request
    .post(`/role/save`, item)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success("操作成功！");
        getDataList();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

// 批量删除
const batchDel = () => {
  console.log(Object.values(selectData.value));
  request
    .post("/role/del", Object.values(selectData.value))
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.msg);
        getDataList();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch((err) => {
      console.log(err);
      ElMessage.error("网络错误");
    });
};

const onSubmit = () => {
  if (
    searchFrom.value.roleName == "" &&
    searchFrom.value.roleKey == "" &&
    searchFrom.value.status == null
  ) {
    return;
  }
  getDataList();
};
const reset = () => {
  searchFrom.value = {
    roleName: "",
    roleKey: "",
    status: null,
  };
  getDataList();
};

// 多选
const handleSelectionChange = (val) => {
  let arr = val.map((item) => item.roleId);

  selectData.value = arr;
  console.log(selectData.value);
  if (selectData.value.length > 0) {
    isBatch.value = false;
  } else {
    isBatch.value = true;
  }
};

onMounted(() => {
  getDataList();
  getMenuList();
});
</script>

<style scoped lang="scss">
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.el-form-item__label {
  font-weight: bold;
}

.el-form {
  display: inline;
}
</style>
import { bind } from "core-js/core/function";
